#!/usr/bin/python3
import os
import time
import zipfile
import shutil
import configparser
import subprocess
import json
import urllib.request
import hashlib

euser={}
eupload={}

euser['host']='http://klipper.youtumao.com/'
euser['temppth']="/home/umeko/printer_data/"
euser['baczip']=euser['temppth']+'tempconfigbackup.zip'

def hash_file(filename):#计算文件哈希值
	hasher = hashlib.md5()
	with open(filename, 'rb') as f:
		buf = f.read()
		hasher.update(buf)
	return hasher.hexdigest()
def compare_files_by_hash(file1, file2):#对比文件是否相同
	return hash_file(file1) == hash_file(file2)

def Is_BackupAuthorize():#判断是否联网
	try:
		with urllib.request.urlopen(euser['host']+'configbackup/authorize/?mac='+euser['mac'], timeout=10) as response:
			if response.getheader('BackupAuthorize')=='1':
				SET_Config(response.getheader('BackupURL'))
				return True
			else:
				return False
	except urllib.error.HTTPError as e:
		return False
	except urllib.error.URLError as e:
		return False
		
def SET_Config(u):#写配置文件
	try:
		if u=="":
			return False
		config = configparser.ConfigParser()
		if not os.path.exists(euser['temppth']+'config/CloudBackup.cfg'):
			config.add_section('CloudBackup')
			config.set('CloudBackup', 'BackupURL', u)
			with open(euser['temppth']+'config/CloudBackup.cfg', 'w') as configfile:
				config.write(configfile)
		else:
			config.read(euser['temppth']+'config/CloudBackup.cfg')
			bacu = config.get('CloudBackup', 'BackupURL')
			if u!=bacu:
				config['CloudBackup']['BackupURL'] = u
				with open(euser['temppth']+'config/CloudBackup.cfg', 'w') as configfile:
					config.write(configfile)
	except Exception as e:
		return False
		
def upload_file():#上传配置文件
	try:
		f_path = euser['baczip']
		fdata=['curl', '--max-time', '30', '-F', 'mac='+euser['mac'],'-F', f'file=@{f_path}', euser['host']+'configbackup/upload/']
		result = subprocess.run(fdata, capture_output=True, text=True)
		try:
			return json.loads(result.stdout)
		except ValueError:
			return {"err":404}
	except Exception as e:
		print(result.stdout)
		return {"err":404}

def get_mac(): #获取MAC
	tem=''
	try:
		result = str(subprocess.run(['ifconfig','-a'],capture_output=True,text=True))
		s_index = result.find('wlan0:')
		if s_index != -1:
			result = result[s_index:]
			s_index = result.find('ether')
			if s_index != -1:
				result = result[s_index:s_index+25]
				tbx=result.split(' ')
				if len(tbx[1])==17:
					tem=tbx[1]
		return tem
	except Exception as e:
		return tem

def compress_config_zip():#压缩文件
	tmpth=euser['temppth']+str(int(time.time()))
	shutil.make_archive(tmpth, 'zip', euser['temppth']+"config/")
	if os.path.exists(tmpth+'.zip'):
		return tmpth+'.zip'
	else:
		return ''

def update_Backup():#更新备份
	temzip=compress_config_zip()
	if not os.path.exists(temzip):
		return False
	if os.path.exists(euser['baczip']):
		if compare_files_by_hash(temzip,euser['baczip']):
			os.remove(temzip)
			return True
		else:
			os.remove(euser['baczip'])
			os.rename(temzip,euser['baczip'])
			#return True
	else:
		os.rename(temzip,euser['baczip'])
		#return True
	ex=upload_file()
	if ex.get('filename',''):
		return True
	else:
		os.remove(temzip)
		return False
		
def Sleep_Backup():#更新配置并等待
	time.sleep(30)
	euser['mac']=get_mac()
	if euser['mac']=='':
		return False
	condition_met=False
	while not condition_met:
		if Is_BackupAuthorize():
			condition_met = True
			if update_Backup():
				print('更新成功')
			else:
				print('更新失败')
		else:
			time.sleep(30)

Sleep_Backup()


